import classnames from 'classnames'
import { useHistory } from 'react-router'
import { NavBar, Search, Dialog } from 'antd-mobile'
import Icon from '@/components/Icon'
import styles from './index.module.scss'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useDebounceFn } from 'ahooks'
import { getSuggestion, addHistory, clearHistory, removeHistory } from '@/store/actions/search'
import { RootState } from '@/types/store'

const SearchPage = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  // 搜索关键字内容
  const [keyword, setKeyword] = useState('')
  // 是否显示搜索
  const [showSuggestion, setShowSuggestion] = useState(false)

  // 获取数据
  const { suggestion, histories } = useSelector((state: RootState) => state.search)

  // 用于生成一个防抖函数
  const { run: getSugguest } = useDebounceFn(
    function () {
      if (!keyword) return
      dispatch(getSuggestion(keyword))
    },
    {
      wait: 500
    }
  )
  // 关键字change
  const onChange = (e: string) => {
    setKeyword(e)
    if (e) {
      setShowSuggestion(true)
      // 获取推荐
      getSugguest()
    } else {
      setShowSuggestion(false)
    }
  }

  // 关键字搜索
  const onSearch = (key: string) => {
    if (!key) return
    dispatch(addHistory(key))
    history.push(`/search/result?key=${key}`)
  }

  // 清除全部历史记录
  const onClearHistory = () => {
    // 清空历史记录
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要清空记录吗？',
      onConfirm: function () {
        dispatch(clearHistory())
      },
    })
  }
  // 历史关键字高亮
  const highLight = (str: string) => {
    return str.replace(
      new RegExp(keyword, 'gi'),
      (match) => `<span>${match}</span>`
    )
  }

  return (
    <div className={styles.root}>
      <NavBar
        className="navbar"
        onBack={() => history.go(-1)}
        right={
          <span
            className="search-text"
            onClick={() => onSearch(keyword)}>
            搜索
          </span>}
      >
        <Search placeholder="请输入关键字搜索"
          value={keyword}
          onChange={onChange} />
      </NavBar>

      {/* 历史记录 */}
      {true && (
        <div
          className="history"
          style={{
            display: showSuggestion ? 'none' : 'block'
          }}
        >
          <div className="history-header">
            <span>搜索历史</span>
            <span onClick={onClearHistory}>
              <Icon type="iconbtn_del" />
              清除全部
            </span>
          </div>

          <div className="history-list">
            {histories.map((item, index) => (
              <span className="history-item" key={index}>
                <span
                  className="text-overflow"
                  onClick={() => onSearch(item)}
                >{item}</span>
                <Icon type="iconbtn_essay_close"
                  onClick={(e) => {
                    e.stopPropagation()
                    dispatch(removeHistory(item))
                  }} />
              </span>
            ))}
          </div>
        </div>
      )}

      {/* 推荐结果 */}
      <div className={classnames('search-result', showSuggestion ? 'show' : '')}>
        {
          suggestion.map((item, index) => (
            <div className="result-item" key={index}>
              <Icon className="icon-search" type="iconbtn_search" />
              <div className="result-value text-overflow"
                dangerouslySetInnerHTML={{
                  __html: highLight(item)
                }}>
              </div>
            </div>
          ))
        }
      </div>
    </div>
  )
}

export default SearchPage
